package cn.edu.swu.book;

import cn.edu.swu.common.UploadUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.JakartaServletFileUpload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet("/AddBook")
public class AddBookServlet extends HttpServlet {

    private static final int MAX_FILE_SIZE =1024*1024*20;       //单文件20MB
    private static final int MAX_REQUEST_SIZE =1024*1024*40;    //总文件40MB


    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //不是多媒体则停止
        if(!JakartaServletFileUpload.isMultipartContent(request)){
            PrintWriter printWriter =response.getWriter();
            printWriter.println("Error:表单必须包含 enctype=multipart/form-data");
            printWriter.flush();
            return;
        }

        DiskFileItemFactory.Builder builder =DiskFileItemFactory.builder();
        builder.setCharset("UTF-8");     //配置参数
        DiskFileItemFactory factory=builder.get();    //get

        JakartaServletFileUpload upload=new JakartaServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderCharset(StandardCharsets.UTF_8);

        String uploadPath =request.getServletContext().getRealPath("./")
                + File.separator+"images"+File.separator+"upload";
        //getrealpath:从servlet在tomcat中的存放文件夹开始计算
        //./意为当前文件夹
        //目录不存在则创建
        File uploadDir=new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }

        try{
            List<FileItem> formItems=upload.parseRequest(request);

            if(!formItems.isEmpty()){
                BOOK book=new BOOK();
                for(FileItem item:formItems){
                    //若是文件(图片)
                    if(!item.isFormField()){
                        //isFormField方法用来判断FileItem对象里面封装的数据是一个普通文本表单字段，还是一个文件表单字段。
                        //如果是普通文本表单字段，返回一个true否则返回一个false。
                        if(item.getName()!=null&&!item.getName().trim().equals("")){
                            File origin =new File(item.getName());
                            String storedFileName= UUID.randomUUID().toString()
                                    + UploadUtils.getFileSuffix(origin);
                            Path filePath = Paths.get(uploadPath,storedFileName);
                            //路径为储存文件夹+储存的文件名
                            System.out.println(filePath);
                            item.write(filePath);
                            book.setPicture(storedFileName);
                        }
                    }else{
                        //其他数据正常处理
                        String name = item.getFieldName();
                        if (name.equals("name")) {
                            book.setName(item.getString());
                        } else if (name.equals("author")) {
                            book.setAuthor(item.getString());
                        } else if (name.equals("price")) {
                            book.setPrice(Float.valueOf(item.getString()));
                        } else if (name.equals("content")) {
                            book.setContent(item.getString());
                        } else if (name.equals("id")) {
                            book.setId(Integer.valueOf(item.getString()));
                        }
                    }
                }

                if(book.getId()==null){
                    bookRepo.getInstance().addBook(book);
                }else{
                    bookRepo.getInstance().updateBook(book);
                }
                response.sendRedirect("./index-simple.html");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /*protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=req.getParameter("name");
        String author=req.getParameter("author");
        String content=req.getParameter("content");
        Float price=Float.valueOf(req.getParameter("price"));

        BOOK book = new BOOK(name, author, content, price);
        try {
            bookRepo.getInstance().addBook(book);
            resp.sendRedirect("./Main");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }*/
}
